package chabernac.android.wordraster.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipFileIterator implements Iterator<String> {
  private static Logger LOGGER = Logger.getLogger(ZipFileIterator.class.getName());
  
  private final ZipInputStream myZipInputStream;
  private final String myExtention;

  private ZipEntry myCurrentEntry = null;
  private BufferedReader myBufferedReader;
  private String myCurrentLine = null;

  public ZipFileIterator(ZipInputStream aZipInputStream, String anExtention) {
    super();
    myZipInputStream = aZipInputStream;
    myExtention = anExtention;
    myBufferedReader = new BufferedReader(new InputStreamReader(myZipInputStream));
  }

  public void close(){
    try {
      myBufferedReader.close();
    } catch (IOException e) {
      LOGGER.log( Level.WARNING, "Could not close stream", e);
    }
  }

  private boolean nextZipEntry(){
    try{
      myCurrentEntry = myZipInputStream.getNextEntry();
      while(myCurrentEntry != null && !myCurrentEntry.getName().endsWith(myExtention)){
        myCurrentEntry = myZipInputStream.getNextEntry();
      }
    }catch(IOException e){
      LOGGER.log( Level.SEVERE, "Could not get next entry from zip file", e);
      return false;
    } finally {
      if(myCurrentEntry == null){
        close();
      }
    }
    
    return myCurrentEntry != null;
  }

  private boolean nextLine(){
    try{
      myCurrentLine  = myBufferedReader.readLine();
      
      if(myCurrentLine == null && nextZipEntry()){
        return nextLine();
      }
    }catch(IOException e){
      LOGGER.log( Level.SEVERE, "could not read next line", e);
      return false;
    }
    
    return myCurrentLine != null;
  }


  @Override
  public boolean hasNext() {
    return nextLine();
  }

  @Override
  public String next() {
    return myCurrentLine;
  }

  @Override
  public void remove() {
    // TODO Auto-generated method stub

  }

}
